<?php
//yiic import test --filename=D:\Book1.xls --model=Test --sheetno=0
class ImportCommand extends CConsoleCommand
{
	public $libPath = 'ext.phpexcel.Classes.PHPExcel.IOFactory';
    public function actionTest($filename, $model, $sheetno=0) 
    {

        echo 'begin:'.date('Y-m-d H:i:s')."\n";
		if(!isset($sheetno))
		{
			$sheetno = 0;
		}
		spl_autoload_unregister(array('YiiBase','autoload'));  
		Yii::import($this->libPath, true);
		$reader = PHPExcel_IOFactory::createReader('Excel5');
		spl_autoload_register(array('YiiBase','autoload'));
		$PHPExcel = $reader->load($filename);
		$sheetData = $PHPExcel->getSheet($sheetno)->toArray(null,true,true,true);
		
        echo "recores number :".count($sheetData)."\n";
        
		$ImportRules = BImport::model()->findAllByAttributes(array('TABLENAME'=>CActiveRecord::model($model)->tableName()));
		
		for ($row = 1; $row <= count($sheetData); $row++)
		{
			$curRow = array();
			foreach ($ImportRules as $rule)
			{
				$curRow[$rule->DATABASE_COLNAME]=$sheetData[$row][$rule->EXCEL_COLNAME];
			}
			$importModel = new $model;
			$importModel->attributes=$curRow;
			$importModel->save();
		}
		
		echo 'end:'.date('Y-m-d H:i:s')."\n";
    }
}